'use strict';

import { Service } from 'egg'
import { UserType } from '../model/user'
import { ModelStatus } from '../model/types'

export default class UserService extends Service {
  
  async create({ name, description }) {
    const { Project } = this.ctx.model as any;
    const findModel = await Project.findWithName(name);
    if (findModel) {
      throw '项目名称已存在'
    }
    const { ctx } = this
    // 获取用户数据
    const userData = await ctx.getUserData()
    const projectModel = new Project({
      name,
      createTime: new Date(),
      description,
      createUser: userData._id
    })
    return await projectModel.save();
  }

  /**
   * 获取个数
   */
  async count() {
    const { Project } = this.ctx.model as any;
    return await Project.findAllCount();
  }

  /**
	 * 获取所有
	 */
  async list() {
    const { Project } = this.ctx.model as any;
    return await Project.findList(this.ctx.query);
  }

  /**
   * 获取所有数据
   */
  async all() {
    const { Project } = this.ctx.model as any;
    return await Project.findAll();
  }

  /**
	 * 删除
	 */
  async remove(id) {
    const { Project } = this.ctx.model as any;
    return await Project.removeProject(id);
  }

  /**
   * 更新项目
   */
  async update(id, { name, description}) {
    const { Project } = this.ctx.model as any;
    return await Project.updateWithId(id, {
      name, description
    });
  }

  /**
   * 获取项目详情
   */
  async show(id) {
    const { User, Project } = this.ctx.model as any;
    const { ctx } = this
    // 获取用户数据
    const userData = await ctx.getUserData()
    // 判断当前账如果是管理员只能查看自己的项目
    const { _id } = userData
    // 根据用户获取项目
    const userModel = await User.findWithID(_id)
    const { projects } = userModel
    if (userModel.type === UserType.ADMIN && !projects.includes(id)) {
      throw '当前账号没有权限查看'
    }
    const model = await Project.findWithID(id);
    if (model.status !== ModelStatus.NORMAL) {
      throw '项目已经删除不能查看'
    }
    return model
  }
}
